package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MyUtil {
    private static SqlSessionFactory MybatisFactory;
    private MyUtil(){

    }

    private static ThreadLocal<SqlSession> sessionThreadLocal = new ThreadLocal<>();

    static {
        try {
            MybatisFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"),"mybatis");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public static SqlSession getMybatisSqlSession(){
        SqlSession session = sessionThreadLocal.get();
        if (session ==null){
            session = MybatisFactory.openSession();
            sessionThreadLocal.set(session);
        }
        return session;
    }

    public static void closeSession(SqlSession sqlSession){
        if (sqlSession!=null){
            sqlSession.close();
            sessionThreadLocal.remove();
        }
    }

}
